package com.tech.koufu.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.Volley;
import com.lidroid.xutils.BitmapUtils;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;
import com.tech.koufu.model.EntrustMsg;
import com.tech.koufu.model.TrackerUser;
import com.tech.koufu.model.UserInfo;
import com.tech.koufu.model.UserStocks;
import com.tech.koufu.tools.CookieStringRequest;
import com.tech.koufu.tools.KouFuTools;
import com.tech.koufu.tools.Statics;
import com.tech.koufu.ui.activity.menu.MyAttentionActivity;
import com.tech.koufu.ui.activity.menu.MyPositionsActivity;
import com.tech.koufu.ui.activity.menu.MyTrackActivity;
import com.tech.koufu.ui.activity.menu.MyTradeActivity;
import com.tech.koufu.ui.adapter.EntrustMsgAdapter;
import com.tech.koufu.ui.adapter.TrackAdapter;
import com.umeng.analytics.MobclickAgent;

import extras.com.handmark.pulltorefresh.library.PullToRefreshBase;
import extras.com.handmark.pulltorefresh.library.PullToRefreshListView;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.util.LruCache;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 用户主页
 * @ClassName: UserDetailActivity
 * @Description: TODO(这里用一句话描述这个类的作用)  
 * @author jl_luo
 * @date 2015年5月9日 上午9:20:30
 */
public class UserDetailActivity extends Activity implements OnClickListener{
	private static final String TAG = UserDetailActivity.class.getName();
	private Context mContext;
	private RequestQueue mQueue; 
	private MyApplication myApp;
	CookieStringRequest stringRequest,loadUserRequest;
	private String userid;
	private String userName;
	private TextView txtConcern,txtTrack;
	private Context context;
	private UserInfo info = new UserInfo();
	private UserStocks ustocks;
	private TextView txt_user_name;
	//总资金，盈利率
	private TextView input_total_money,input_profitrate_ss,input_date_gains,
	input_month_gains,input_suss_rate,input_compe_rank,input_user_level,
	input_stock_price;
	
	private RelativeLayout rl_tab_index,rl_tab_nr,rl_tab_hq,rl_tab_ss;
	private TextView txt_tab_index,txt_tab_nr,txt_tab_hq,txt_tab_ss,
	txt_begin_funds,input_canuse_price,txt_week_gains_u,txt_positions_value;
	private View v_tab_index,v_tab_nr,v_tab_hq,v_tab_ss;
//	private ArrayList<EntrustMsg> datas;
//	private PullToRefreshListView mPullToRefreshListView;
//	private ListView actualListView;
//	private EntrustMsgAdapter mAdapter;
//	private LinearLayout topView;
//	private int page = 1;
	private WebView imgMsgWebView;
	@Override
	protected void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detail_user);
		userid = getIntent().getStringExtra("userid");
		userName = getIntent().getStringExtra("username");
		context = getApplicationContext();
		mContext = this;
		initView();
		initData();
		initTab();
	}
	
	 @Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(mContext);
	}
	 
	 @Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(mContext);
	}
	 
	private void initView(){
		
//		topView = (LinearLayout) LayoutInflater.from(getApplicationContext()).inflate(R.layout.user_detail_lv_top, null,false);
		
		txtConcern = (TextView)findViewById(R.id.txt_concern);
		txtTrack = (TextView)findViewById(R.id.txt_track);
		txtConcern.setOnClickListener(this);
		txtTrack.setOnClickListener(this);
		findViewById(R.id.img_callback).setOnClickListener(this);
		txt_user_name = (TextView)findViewById(R.id.txt_user_name);
		
		input_total_money = (TextView)findViewById(R.id.input_total_money);
		input_profitrate_ss = (TextView)findViewById(R.id.input_profitrate_ss);
		input_date_gains = (TextView)findViewById(R.id.input_date_gains);
		input_month_gains = (TextView)findViewById(R.id.input_month_gains);
		input_suss_rate = (TextView)findViewById(R.id.input_suss_rate);
		input_compe_rank = (TextView)findViewById(R.id.input_compe_rank);
		input_user_level = (TextView)findViewById(R.id.input_user_level);
		input_stock_price = (TextView)findViewById(R.id.input_stock_price);
		txt_begin_funds = (TextView)findViewById(R.id.txt_begin_funds);
		input_canuse_price = (TextView)findViewById(R.id.input_canuse_price);
		txt_week_gains_u = (TextView)findViewById(R.id.txt_week_gains_u);
		txt_positions_value = (TextView)findViewById(R.id.txt_positions_value);
//		mPullToRefreshListView = (PullToRefreshListView)findViewById(R.id.lv_pull);
//		actualListView = mPullToRefreshListView.getRefreshableView(); 
//        registerForContextMenu(actualListView);
//        actualListView.addHeaderView(topView);
		
		imgMsgWebView = (WebView)findViewById(R.id.iv_img_msg);
	}
	private void initData(){
//		datas = new ArrayList<EntrustMsg>();
		mQueue = Volley.newRequestQueue(getApplicationContext());  
		myApp = (MyApplication) getApplication(); 
		txt_user_name.setText(userName);
		if(userid.equals(myApp.getUserid())){
			((TextView)findViewById(R.id.tv_title)).setText("我的主页"); 
			txtConcern.setVisibility(View.GONE);
			txtTrack.setVisibility(View.GONE);
		}else{
			((TextView)findViewById(R.id.tv_title)).setText("用户信息");
		} 
//		mAdapter = new EntrustMsgAdapter(getApplicationContext());
//		actualListView.setAdapter(mAdapter);
//		initMsg();
		load(); 
		displayImgMsg();
	}
//	private void initMsg(){
//		mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
//
//			@Override
//			public void onRefresh(PullToRefreshBase<ListView> refreshView) { 
//				Mode mode = mPullToRefreshListView.getCurrentMode(); 
//		        if(mode == Mode.PULL_FROM_START) { 
//		        	datas.clear();
//		        	page=1; 
//		        }else {
//		        	page++; 
//		        }   
//				loadMsg();
//			}
//		});
//		mPullToRefreshListView.setRefreshing(true);
//		mPullToRefreshListView.setMode(Mode.BOTH);
//	}
	
	
	private void showDetail(){
		if(info!=null){
			input_total_money.setText(info.getAllMoney());
			
			String yll = info.getYll() + "%";
			SpannableStringBuilder style=new SpannableStringBuilder();
			KouFuTools.setValueColor(context, input_profitrate_ss, 0,  yll.length(), info.getYll() + "%", yll);
			
			
			String ryl =  info.getRyl();
			KouFuTools.setValueColor(context, input_date_gains, 0,  ryl.length(), info.getRyl(), ryl);
			
			
			Float ylzj = Float.valueOf(info.getAllMoney()) - Float.valueOf(info.canUseMoney);
			String gpv =  KouFuTools.df2.format(ylzj); 
			KouFuTools.setValueColor(context, input_stock_price, 0,  gpv.length(), ylzj+"", gpv);
			
			
			String yyl = info.getYyl() + "%"; 
			KouFuTools.setValueColor(context, input_month_gains, 0,  yyl.length(), info.getYyl(), yyl);
			
			
			
			String cgl =  info.getCgl() + "%";
			style=new SpannableStringBuilder(cgl); 
			style.setSpan(new ForegroundColorSpan(context.getResources()
					.getColor(R.color.bgBlackColor_63)), 0, 0,
					Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
			input_suss_rate.setText(style);
			
			String pm =  info.getPm();
			style=new SpannableStringBuilder(pm); 
			style.setSpan(new ForegroundColorSpan(context.getResources()
					.getColor(R.color.TextColorRed_FD0000)), 0,pm.length(),
					Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
			input_compe_rank.setText(style);
			
			
			String dw =  info.getPj();
			style=new SpannableStringBuilder(dw); 
			style.setSpan(new ForegroundColorSpan(context.getResources()
					.getColor(R.color.txtColorYellow_dd9800)), 0,dw.length(),
					Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
			input_user_level.setText(style);
			
			txt_begin_funds.setText(info.beginMoney);
			input_canuse_price.setText(info.canUseMoney);
			
			String zyl = info.zyl + "%";
			KouFuTools.setValueColor(context, txt_week_gains_u, 0,  zyl.length(), info.getZyl(), zyl);
			
			txt_positions_value.setText(info.cw);
		}
	}
	private void load(){
		String url = myApp.url+"Userinfo.dll";
		final String t = KouFuTools.readTimeInfo(new String());
		loadUserRequest = new CookieStringRequest(Method.POST, url, new Listener<String>() {

			@Override
			public void onResponse(String response) {    
				if(!TextUtils.isEmpty(response)){
					try {   
						parseUserInfoJsonString(response);
						parseStocksInfoJsonString(response);
						showDetail();
					} catch (Exception e) { 
						e.printStackTrace();
					}
				} 
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) { 
				
			}
		}){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError { 
				Map<String, String> params = new HashMap<String, String>();  
				params.put("userid", myApp.getUserid());
				params.put("time", t);
				params.put("login", "1");
				return params;
			}
		}; 
		String cookie = KouFuTools.descrypt(myApp.getUserid() + t );
		loadUserRequest.setHeader(cookie);
		loadUserRequest.setCharset("GBK");
		mQueue.add(loadUserRequest);
	}
	private void parseUserInfoJsonString(String returnValue){
//		Log.v(TAG, "1:"+returnValue);
		if (returnValue.substring(0, 1).equals("0")) {
			String[] us = returnValue.trim().substring(2, returnValue.lastIndexOf("|")).split(",");
			Log.v(TAG, returnValue.substring(2, returnValue.lastIndexOf("|")).toString());
			info.setTeamid(us[0].toString());
			info.setXzmc(us[1].toString());
			info.setZqlb(us[2].toString());
			String[] money = us[3].toString().split("\\|");
			info.setBeginMoney(money[0].toString());
			info.setCanUseMoney(money[1].toString());
			info.setAllMoney(us[4].toString());
			info.setRjyl(us[5].toString());
			info.setRyl(us[6].toString());
			info.setZyl(us[7].toString());
			info.setYyl(us[8].toString());
			info.setYll(us[9].toString());
			info.setCgl(us[10].toString());
			info.setZzl(us[11].toString());
			info.setPm(us[12].toString());
			info.setSj(us[13].toString());
			info.setCw(us[14].toString());
			info.setPj(us[15].toString()); 
//			Log.v(TAG, "2:"+info.toString());

		}else {
			Toast.makeText(context, "返回数据失败："+returnValue, Toast.LENGTH_LONG).show();
		}
	}
	private ArrayList<UserStocks> list = new ArrayList<UserStocks>(); 
	private void parseStocksInfoJsonString(String returnValue){
		if (returnValue.substring(0, 1).equals("0")) {
			String[] us = returnValue.trim().substring(returnValue.lastIndexOf("|")+1,returnValue.length()).split(";");
//			Log.v(TAG,  returnValue.substring(returnValue.lastIndexOf("|"),returnValue.length()).toString());
			for(int i=0;i<us.length;i++){
				ustocks = new UserStocks();
				String[] a =  us[i].split(",");
				ustocks.setStockId(a[0].toString().trim());
				ustocks.setStockName(a[1].toString().trim());
				ustocks.setStockHold(a[2].toString().trim());
				ustocks.setStockbj(a[4].toString().trim());
				ustocks.setAllmoney(info.getAllMoney());
				ustocks.setTeamId(info.getTeamid());
				list.add(ustocks);
//				stockparms.append(","+ustocks.getStockId());

			}
//			myApp.mUserStocks = list;
//			Log.v("stockParms=====>", stockparms.toString());
//			Log.v(TAG, list.toString());
//			if(stockparms.length()>1){
//				getUserStocksInfo();
//			}
		}
	}
//	private void loadMsg(){
//		String url = Statics.URL_PHP+Statics.IF_entrust; 
//		stringRequest = new CookieStringRequest(Method.POST, url, new Listener<String>() {
//
//			@Override
//			public void onResponse(String response) {    //Log.w("Tt", "~~"+response);
//				if(!TextUtils.isEmpty(response)){
//					try {   
//						 JSONObject object = new JSONObject(response);
//						 int status = object.optInt("status"); 
//						 if(status==0){
//							 JSONArray daa = object.optJSONArray("data");
//							 for(int i=0;i<daa.length();i++){
//								 datas.add(new EntrustMsg(daa.getJSONObject(i)));
//							 }
//							 mAdapter.datas = datas;
//							 mAdapter.notifyDataSetChanged();
//							 //Log.w("Tt", "~~~~~~~"+datas.size());
//						 }else{
//							 
//						 }
//					} catch (Exception e) { 
//						e.printStackTrace();
//					}
//				} 
//				mPullToRefreshListView.onRefreshComplete();
//			}
//		}, new ErrorListener() {
//
//			@Override
//			public void onErrorResponse(VolleyError error) { 
//				 Log.w("Tt", "~~~~~~~"+error.getMessage());
//				 mPullToRefreshListView.onRefreshComplete();
//			}
//		}){
//			@Override
//			protected Map<String, String> getParams() throws AuthFailureError { 
//				Map<String, String> params = new HashMap<String, String>();   
//				params.put("userID", Statics.test_user_id);//Statics.test_user_id "477699"
//				params.put("page", page+"");    
//				return params;
//			}
//		}; 
//		stringRequest.setHeader(myApp.phpsessid);
//		mQueue.add(stringRequest);
//	}
	
	private void displayImgMsg(){ 
		String imgURL = Statics.URL_zousi+userid;
		//"1964X2796226";//userid;//"http://www1.cofool.com/api/app_zichanzoushi_pic.asp?uid=100X2856835";
		Log.d(TAG, "imgURL="+imgURL);
		imgMsgWebView.loadUrl(imgURL);
	}
	 
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			this.finish();
			
			return true;
		}
		
		return super.onKeyDown(keyCode, event);
	}
	@Override
	public void onClick(View v) { 
		switch (v.getId()) {
		case R.id.txt_concern:
			String text = txtConcern.getText().toString();
			if(text.equals(getResources().getString(R.string.txt_concern))){
				action(3);
			}else{
				action(4);
			}
			
			break;
			
		case R.id.txt_track:
			text = txtTrack.getText().toString();
			if(text.equals(getResources().getString(R.string.txt_track))){
				action(1);
			}else{
				action(2);
			}
			 
			break;
		case R.id.img_callback:
			this.finish();
			break;
		case R.id.rl_tab_index:
			if(v_tab_index.getVisibility() != View.VISIBLE){  
				resetTabLine();
				showTabLine(v_tab_index);
				changeTextColor(txt_tab_index, R.color.kfColorRed);
			}
			Intent intent = new Intent(UserDetailActivity.this,MyAttentionActivity.class);
//			intent.putExtra("status", 3);
			intent.putExtra("userid", userid);
			startActivity(intent);
			
			break;
		case R.id.rl_tab_nr:
			if(v_tab_nr.getVisibility() != View.VISIBLE){  
				resetTabLine();
				showTabLine(v_tab_nr);
				changeTextColor(txt_tab_nr, R.color.kfColorRed);
			}
			intent = new Intent(UserDetailActivity.this,MyTrackActivity.class); 
			intent.putExtra("userid", userid);
			startActivity(intent);
			break;
		case R.id.rl_tab_hq:
			if(v_tab_hq.getVisibility() != View.VISIBLE){  
				resetTabLine();
				showTabLine(v_tab_hq);
				changeTextColor(txt_tab_hq, R.color.kfColorRed);
			}
			intent = new Intent(UserDetailActivity.this,MyPositionsActivity.class); 
			intent.putExtra("userid", userid);
			startActivity(intent);
			break;
		case R.id.rl_tab_ss:
			if(v_tab_ss.getVisibility() != View.VISIBLE){  
				resetTabLine();
				showTabLine(v_tab_ss);
				changeTextColor(txt_tab_ss, R.color.kfColorRed);
			}
			intent = new Intent(UserDetailActivity.this,MyTradeActivity.class); 
			intent.putExtra("userid", userid);
			startActivity(intent);
			break;
		default:
			break;
		}
	}
	/**
	 * 
	* @Title: action 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param type    1.追踪，2：取消追踪，3，关注，4：取消关注
	* @return void    返回类型 ：
	* @throws
	 */
	private void action(final int type){
		String url = null;
		if(type==1){
			url = Statics.URL_PHP+Statics.IF_addTrack; 
		}else if(type==2){
			url = Statics.URL_PHP+Statics.IF_removeTrack; 
		}else if(type==3){
			url = Statics.URL_PHP+Statics.IF_addConcern;
		}else{
			url = Statics.URL_PHP+Statics.IF_removeConcern;
		}
		
		stringRequest = new CookieStringRequest(Method.POST, url, new Listener<String>() {

			@Override
			public void onResponse(String response) {   
				if(!TextUtils.isEmpty(response)){
					try {  
						JSONObject obj = new JSONObject(response);
						String status = obj.optString("status");
						String data = obj.optString("data");
						Toast.makeText(context, data, Toast.LENGTH_SHORT).show();
						if(status.equals("0")){
							if(type==1){  //追踪成功
								txtTrack.setText(R.string.txt_tracked); 
							}else if(type==2){  //取消追踪成功
								txtTrack.setText(R.string.txt_track);
							}else if(type==3){ //关注成功
								txtConcern.setText(R.string.txt_concerned);
							}else{ //取消关注成功
								txtConcern.setText(R.string.txt_concern);
							}
						}
					} catch (JSONException e) { 
						e.printStackTrace();
					}
				} 
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) { 
				
			}
		}){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError { 
				Map<String, String> params = new HashMap<String, String>(); 
				params.put("tracker_id", userid);   
				params.put("concern_user_id", userid);  
				params.put("tracker_name", userName);
				params.put("concern_user_name", userName);
				return params;
			}
		}; 
		stringRequest.setHeader(myApp.phpsessid);
		mQueue.add(stringRequest);
	}
	
	private void initTab(){
		rl_tab_index = (RelativeLayout)findViewById(R.id.rl_tab_index);
		rl_tab_nr = (RelativeLayout)findViewById(R.id.rl_tab_nr);
		rl_tab_hq = (RelativeLayout)findViewById(R.id.rl_tab_hq);
		rl_tab_ss = (RelativeLayout)findViewById(R.id.rl_tab_ss);
		rl_tab_index.setOnClickListener(this);
		rl_tab_nr.setOnClickListener(this);
		rl_tab_hq.setOnClickListener(this);
		rl_tab_ss.setOnClickListener(this);
		txt_tab_index = (TextView)findViewById(R.id.txt_tab_index);
		txt_tab_nr = (TextView)findViewById(R.id.txt_tab_nr);
		txt_tab_hq = (TextView)findViewById(R.id.txt_tab_hq);
		txt_tab_ss = (TextView)findViewById(R.id.txt_tab_ss);
		v_tab_index = (View)findViewById(R.id.v_tab_index);
		v_tab_nr = (View)findViewById(R.id.v_tab_nr);
		v_tab_hq = (View)findViewById(R.id.v_tab_hq);
		v_tab_ss = (View)findViewById(R.id.v_tab_ss);
	}
	
	private void resetTabLine(){ 
		v_tab_index.setVisibility(View.INVISIBLE);
		v_tab_nr.setVisibility(View.INVISIBLE);
		v_tab_hq.setVisibility(View.INVISIBLE);
		v_tab_ss.setVisibility(View.INVISIBLE);
		
		txt_tab_index.setTextColor(getResources().getColor(R.color.textColorGray_888888));
		txt_tab_nr.setTextColor(getResources().getColor(R.color.textColorGray_888888));
		txt_tab_hq.setTextColor(getResources().getColor(R.color.textColorGray_888888));
		txt_tab_ss.setTextColor(getResources().getColor(R.color.textColorGray_888888));
	}
	private void showTabLine(View v){
		v.setVisibility(View.VISIBLE);
	}
	private void changeTextColor(TextView tv,int colors){
		tv.setTextColor(getResources().getColor(colors));
	}
	@Override
	protected void onStop() { 
		super.onStop();
		if(stringRequest!=null){
			mQueue.cancelAll(stringRequest);
		}
		if(loadUserRequest!=null){
			mQueue.cancelAll(loadUserRequest);
		}
	}
}
